<template>
  <!-- 购物车列表 -->
  <div class="container">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th clearfix">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cart in cartInfoList" :key="cart.id">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              id=""
              value=""
              :checked="cart.isChecked == 1"
              @change="updateChecked(cart, $event)"
            />
          </li>
          <li class="cart-list-con2">
            <img v-lazy="cart.imgUrl" />
            <div class="item-msg">{{ cart.skuName }}</div>
          </li>

          <li class="cart-list-con3">
            <div class="item-txt">墨绿色</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cart.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <div class="box">
              <a
                href="javascript:void(0)"
                class="mins"
                @click="handler('minus', -1, cart)"
                >-</a
              >
              <input
                autocomplete="off"
                type="text"
                :value="cart.skuNum"
                minnum="1"
                class="itxt"
                @change="handler('change', $event.target.value * 1, cart)"
              />
              <a
                href="javascript:void(0)"
                class="plus"
                @click="handler('add', 1, cart)"
                >+</a
              >
            </div>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cart.skuNum * cart.skuPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="btn" @click="deleteCartById(cart)">删除</a>
            <br />
            <a>移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input
          class="chooseAll"
          type="checkbox"
          v-model="isAllCheck"
          @change="updateAllCartChecked"
        />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="#" @click="deleteAll" class="btn">删除选中的商品</a>
        <a>移到我的关注</a>
        <a>清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span class="summoney">{{ totalNum }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <a href="#" class="sum-btn" @click="goCalc">结算</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "ShopCart",

  data() {
    return {};
  },

  mounted() {
    this.getData();
  },
  computed: {
    ...mapGetters("shopcart", ["cartList"]),
    cartInfoList() {
      return this.cartList.cartInfoList || [];
    },
    totalNum() {
      return this.cartInfoList
        .filter((item) => item.isChecked == 1)
        .reduce((prev, current) => {
          return prev + current.skuNum;
        }, 0);
    },

    //    totalPrice() {
    //       let sum = 0;
    //       this.cartInfoList.forEach((item) => {
    //         sum += item.skuNum * item.skuPrice;
    //       });
    //       return sum;
    //     },

    totalPrice() {
      return this.cartInfoList
        .filter((item) => item.isChecked == 1)
        .reduce((pre, item) => {
          return (pre += item.skuNum * item.skuPrice);
        }, 0);
    },
    // /判断底部复选框是否勾选【全部产品都选中，采勾选】
    isAllCheck: {
      get() {
        return (
          this.cartInfoList.length > 0 &&
          this.cartInfoList.every((item) => item.isChecked == 1)
        );
      },
      //遍历数组里面原理，只要全部元素isChecked属性都为1===>真 true
      //只要有一个不是1======>假false
    },
  },
  methods: {
    goCalc() {
      if (this.totalPrice == 0) {
        this.$message.error("请选择至少一项");
        return;
      }
      this.$router.push("/trade");
    },
    deleteCartById(cart) {
      this.$confirm(`此操作将永久删除该${cart.skuName}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.$store.dispatch("shopcart/deleteId", cart.skuId);
          this.$message.success("删除成功");
          this.getData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteAll() {
      this.$confirm(`此操作将永久删除该, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await this.$store.dispatch("shopcart/deleteAllChecked");
            this.$message.success("删除成功");
            this.getData();
          } catch (e) {
            alert(e);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    getData() {
      this.$store.dispatch("shopcart/getCartList");
    },
    async updateChecked(cart, e) {
      //带给服务器的参数isChecked，不是布尔值，应该是0|1
      console.log(cart, e.target.checked);
      let isChecked = e.target.checked ? 1 : 0;
      try {
        await this.$store.dispatch("shopcart/updateCheckedById", {
          skuId: cart.skuId,
          isChecked,
        });
        this.getData();
      } catch (e) {
        alert(e);
      }
    },
    //修改全部产品的选中状态
    async updateAllCartChecked(event) {
      try {
        let isChecked = event.target.checked ? "1" : "0";
        //派发action
        await this.$store.dispatch(
          "shopcart/updateAllCartIsChecked",
          isChecked
        );
        this.getData();
      } catch (error) {
        alert(error.message);
      }
    },

    //   }).then(async () => {
    //     await this.$store.dispatch("shopcart/deleteId", cart.skuId);
    //     this.$message.success("删除成功!");
    //     this.getData();
    //   });
    async handler(type, disNum, cart) {
      switch (type) {
        //加号
        case "add":
          disNum = 1;
          break;
        case "minus":
          //判断产品的个数大于1，才可以传递给服务器-1   @click="skuNum > 1 ? skuNum-- : (skuNum = 1)"
          //如果出现产品的个数小于等于1，传递给服务器个数0（原封不动）
          disNum = cart.skuNum > 1 ? -1 : 0;
          break;
        case "change":
          // //用户输入进来的最终量，如果非法的（带有汉字|出现负数），带给服务器数字零
          if (isNaN(disNum) || disNum < 1) {
            disNum = 0;
          } else {
            //属于正常情况（小数：取证），带给服务器变化的量 用户输入进来的 - 产品的起始个数
            disNum = parseInt(disNum) - cart.skuNum;
          }
          // disNum = (isNaN(disNum)||disNum<1)?0:parseInt(disNum) - cart.skuNum;
          break;
      }
      try {
        //代表的是修改成功
        await this.$store.dispatch("detail/addShopCart", {
          skuId: cart.skuId,
          skuNum: disNum,
        });
        //再一次获取服务器最新的数据进行展示
        this.getData();
      } catch (error) {
        alert(error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
h4 {
  margin: 9px 0;
  font-size: 14px;
  line-height: 21px;
}
input {
  vertical-align: middle;
}

span {
  vertical-align: middle;
}
.cart-main {
  //标题
  .cart-th {
    background: #f5f5f5;
    border: 1px solid #ddd;
    padding: 10px;

    & > div {
      float: left;
    }

    .cart-th1,
    .cart-th2 {
      width: 25%;
    }

    .cart-th3,
    .cart-th4,
    .cart-th5,
    .cart-th6 {
      width: 12.5%;
    }
  }
  .cart-body {
    margin: 15px 0;
    border: 1px solid #ddd;

    .cart-list {
      padding: 10px;
      border-bottom: 1px solid #ddd;
      overflow: hidden;
      & > li {
        float: left;
      }

      .cart-list-con1 {
        width: 15%;
      }

      .cart-list-con2 {
        width: 30%;

        img {
          width: 82px;
          height: 82px;
          float: left;
        }

        .item-msg {
          float: left;
          width: 150px;
          margin: 0 10px;
          line-height: 18px;
        }
      }
      .cart-list-con3 {
        width: 5%;
      }
      .cart-list-con4 {
        width: 10%;
      }
      .cart-list-con5 {
        width: 15%;
        .box {
          display: flex;
        }
        a {
          border: 1px solid #ddd;
          color: #666;
          width: 6px;

          text-align: center;
          padding: 8px;
        }

        input {
          width: 40px;
          height: 33px;

          text-align: center;
          font-size: 14px;
        }
      }
      .cart-list-con6 {
        width: 13%;

        .sum {
          font-size: 16px;
        }
      }

      .cart-list-con7 {
        width: 10%;

        a {
          cursor: pointer;
          color: rgb(51, 37, 37);
        }
      }
    }
  }
}

.cart-tool {
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .select-all {
    padding: 10px;

    span {
      vertical-align: middle;
    }

    input {
      vertical-align: middle;
    }
  }

  .option {
    padding: 10px;

    a {
      float: left;
      padding: 0 10px;
      color: rgb(24, 22, 22);
    }
  }

  .money-box {
    line-height: 52px;
    height: 52px;
    .chosed {
      float: left;
      padding: 0 10px;
    }

    .sumprice {
      width: 200px;

      float: left;
      padding: 0 10px;
    }
    .summoney {
      color: #c81623;
      font-weight: bold;
      font-size: 16px;
    }
    .sumbtn {
      float: right;

      a {
        display: block;
        position: relative;
        width: 96px;
        height: 52px;
        line-height: 52px;
        color: #fff;
        text-align: center;
        font-size: 18px;
        font-family: "Microsoft YaHei";
        background: #e1251b;
        overflow: hidden;
      }
    }
  }
}
a.btn {
  height: 22px;
  line-height: 22px;
  padding: 0 10px;
  text-align: center;
  color: #fff !important;
  font-family: "Microsoft YaHei";
  background: #e1251b;
}
</style>
